package com.example.springstack.springsecurity.service.impl;

import com.example.springstack.springsecurity.entity.User;
import com.example.springstack.springsecurity.service.MyAccess;
import org.springframework.http.HttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.Collection;

/**
 * @author qiangfanghao
 * @date
 */
@Service("myAccess")
public class MyAccessImpl implements MyAccess {
    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        //获取当前登录 URI
        String requestURI = request.getRequestURI();
        //获取当前登录用户
        Object principal = authentication.getPrincipal();
        if (principal instanceof User){
            User user = (User) principal;
            //获取所有权限
            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
            boolean contains = authorities.contains(new SimpleGrantedAuthority(requestURI));
            return contains;
        }

        return false;
    }
}
